package logic

import (
	"context"
	"encoding/json"
	"product/model/cache"
	"product/model/mysql"
	"time"

	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProducthotListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProducthotListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProducthotListLogic {
	return &ProducthotListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 热度前十
func (l *ProducthotListLogic) ProducthotList(in *productrpc.ProducthotListRequest) (*productrpc.ProducthotListResponse, error) {
	// todo: add your logic here and delete this line
	var product []mysql.Products

	mysql.DB.Debug().Limit(10).Order("browse_number desc").Find(&product)

	result, _ := cache.Rdb.Get(l.ctx, "ProductList").Result()
	if result == "" {

		marshal, _ := json.Marshal(&product)
		cache.Rdb.Set(l.ctx, "ProductList", marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(result), &product)
	}

	var productlists []*productrpc.ProductList
	for _, i2 := range product {
		list := productrpc.ProductList{
			Title:        i2.Title,
			UserId:       i2.UserId,
			Price:        float32(i2.Price),
			BrowseNumber: i2.BrowseNumber,
			Image:        i2.Image,
			ClassId:      i2.ClassId,
		}
		productlists = append(productlists, &list)
	}
	return &productrpc.ProducthotListResponse{}, nil
}
